import { ComponentPublicInstance, createApp } from 'vue';
// import ElementPlus, { ElMessage } from 'element-plus';
// import 'element-plus/lib/theme-chalk/index.css';
import {
  ElButton,
  ElSelect,
  ElMessage,
  ElForm,
  ElFormItem,
  ElIcon,
  ElTree,
  ElMain,
  ElAside,
  ElInput,
  ElOption,
  ElDialog,
  ElContainer,
  ElMenu,
  ElMenuItem,
  ElSubmenu,
  ElMenuItemGroup,
  ElTooltip
} from 'element-plus';

import App from './App.vue';
import router from './router';
import UserService from '@/services/user.service';
import NetService, { FaceError, SocketStatus } from '@/services/net.service';

const errorHandler = (err: unknown, vm: ComponentPublicInstance<Any>) => {
  if (err instanceof FaceError) {
    let message = '';
    switch (err.code) {
    case SocketStatus.DISCONNECT:
      message = '连接已断开！';
      break;
    case SocketStatus.NOTFOUND:
      message = err.message ?? '接口不存在！';
      break;
    case SocketStatus.TIMEOUT:
      message = '访问超时！';
      break;
    case SocketStatus.INVALID:
      message = '接口参数错误！';
      break;
    case SocketStatus.NOTPERMITED:
      message = '没有接口权限！';
      break;
    case SocketStatus.UNAUTHORIZED:
      message = '登陆过期！';
      setTimeout(() => {
        let path = '/';
        if (vm) {
          path = vm.$route.path;
        }
        if (path === '/user/signin') {
          return;
        }
        location.href = '/user/signin?redirect=' + path;
      }, 100);
      break;
    case SocketStatus.ERROE:
      message = err.message;
      break;
    default:
      message = err.message;
    }
    if (vm) {
      ElMessage.closeAll();
      ElMessage.error(message);
    }
  } else {
    console.error(err);
  }
};

class Entry {
  constructor () {
    this.setup();
  }

  private async setup () {
    let app = createApp(App).use(router)
      .use(ElAside)
      .use(ElButton)
      .use(ElForm)
      .use(ElFormItem)
      .use(ElIcon)
      .use(ElInput)
      .use(ElMain)
      .use(ElSelect)
      .use(ElTree)
      .use(ElOption)
      .use(ElDialog)
      .use(ElContainer)
      .use(ElMenu)
      .use(ElMenuItem)
      .use(ElSubmenu)
      .use(ElMenuItemGroup)
      .use(ElTooltip);
    let vm = app.mount('#app');
    const netService = new NetService();
    netService.errorHandler = (err) => {
      errorHandler(err, vm);
    };
    let userService = new UserService();
    try {
      await userService.load();
    } catch {
      vm.$router.replace('/user/signin');
    }
  }
}

// eslint-disable-next-line no-new
new Entry();

window.addEventListener('error', event => {
  event.preventDefault();
  console.log('严重错误:');
  console.error(event);
});
window.addEventListener('unhandledrejection', event => {
  event.preventDefault();
  console.log('严重错误:');
  console.error(event);
});
